<?php

namespace app\health\controller;

use app\health\model\HealthUser;
use app\health\service\WeMiniService;
use app\health\validate\LoginValidate;
use Exception;
use fast\Random;
use think\exception\DbException;
use think\Request;

class Login extends ApiBase
{
    protected $noNeedLogin = ['wnpMobileLogin', 'mobile', 'mock', 'wnpLogin', 'wnpIsRegister','chongqingLogin'];

    /**
     * 获取当前用户是否注册
     * @return void
     * @throws Exception
     */
    public function wnpIsRegister(): void
    {
        $params              = (new LoginValidate())->goCheck('wnpLogin');
        $weSession           = WeMiniService::getWeLoginSession($params['wx_login_code']);
        $openId              = $weSession['openid'] ?? '';
        $data['is_register'] = 0;
        $user                = empty($openId) ? null : HealthUser::getByOpenid($openId);
        if ($user) {
            $data['is_register'] = 1;
        }
        $this->success('success', $data);

    }

    /**
     * 微信授权登录
     * @return void
     * @throws DbException
     */
    public function wnpLogin(): void
    {
        $params    = (new LoginValidate())->goCheck('wnpLogin');
        $weSession = WeMiniService::getWeLoginSession($params['wx_login_code']);
        if (empty($weSession['openid'])) {
            $this->error('登录失败');
        }
        $openId = $weSession['openid'] ?? '';
        $user   = HealthUser::getByOpenid($openId);
        if ($user) {
            $this->auth->direct($user->id);
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        }
        $this->error('用户未注册');
    }

    /**
     * 微信手机授权登录
     * @return void
     * @throws Exception
     */
    public function wnpMobileLogin()
    {
        $scene       = $this->request->param('scene', '');
        $channel_id  = $this->request->param('channel_id', 0);
        $platform    = $this->request->param('platform', '');
        $params      = (new LoginValidate())->goCheck('wnpMobileLogin');
        $phone       = WeMiniService::getPhoneNumber($params['wx_phone_code']);
        $weSession   = WeMiniService::getWeLoginSession($params['wx_login_code']);
        $openId      = $weSession['openid'];
        $session_key = $weSession['session_key'] ?? '';
        Request::instance()->bind('user_mobile', $phone);
        $user        = HealthUser::getByMobile($phone);
        $channelData = compact('scene', 'channel_id', 'platform');
        if (!$user) { //未注册用户
            $user = $this->auth->register($phone, $openId, $session_key, $channelData);
        } else {
            $user->openid      = $openId;
            $user->session_key = $session_key;
            $user->save();
        }
        $this->auth->direct($user->id);
        $data = ['userinfo' => $this->auth->getUserinfo()];
        $this->success(__('Logged in successful'), $data);
    }

    /**
     * 手机号验证码登录
     * @return void
     * @throws Exception
     */
    public function mobile(): void
    {
        $scene      = $this->request->param('scene', '');
        $channel_id = $this->request->param('channel_id', 0);
        $platform   = $this->request->param('platform', '');
        $params     = (new LoginValidate())->goCheck('mobile', ['scene' => 'login']);
        Request::instance()->bind('user_mobile', $params['mobile']);
        $weSession   = WeMiniService::getWeLoginSession($params['wx_login_code']);
        $openId      = $weSession['openid'] ?? '';
        $session_key = $weSession['session_key'] ?? '';
        $user        = HealthUser::getByMobile($params['mobile']);
        $channelData = compact('scene', 'channel_id', 'platform');
        if (!$user) { //未注册用户
            $user = $this->auth->register($params['mobile'], $openId, $session_key, $channelData);
        } else {
            $user->openid      = $openId;
            $user->session_key = $session_key;
            $user->save();
        }
        $this->auth->direct($user->id);
        $data = ['userinfo' => $this->auth->getUserinfo()];
        $this->success(__('Logged in successful'), $data);
    }

    /**
     * 模拟登录
     * @Author 张旭鹏
     * @DateTime 2023-07-04
     */
    public function mock(): void
    {
        $mobile = $this->request->param('mobile', '17733829326');
        $key    = $this->request->param('key', '');
        if ($key !== 'eRYnI6rjcbrfvgVj') {
            $this->error('非法请求');
        }
        Request::instance()->bind('user_mobile', $mobile);
        $user = HealthUser::getByMobile($mobile);
        if (!$user) { //未注册用户
            $this->error('用户未注册');
        }
        $this->auth->direct($user->id);
        $data = ['userinfo' => $this->auth->getUserinfo()];
        $this->success(__('Logged in successful'), $data);
    }
    public  function chongqingLogin(){
        $param = $this->request->param();
//        $encryptData = $this->encrypt('{"phone":"15032189134","timestamp":"20250110150030"}','lkji4uioas2q','xo1i7edhq5sj');
//        halt($encryptData);
        //拿到加密的信息去进行解密
        $decryptData = $this->decrypt($param['encrypt'],'lkji4uioas2q','xo1i7edhq5sj');
//        halt($decryptData);
        if($decryptData === false){
            $this->error('解密失败');
        }
        $data = json_decode($decryptData,true);
//        halt($data);
        //判断手机号是否绑定过其他的openid
        $user        = HealthUser::getByMobile($data['phone']);
        if (!$user) { //未注册用户
            $user = $this->auth->register($data['phone'], '', '');
        }
        $this->auth->direct($user->id);
        $data = ['userinfo' => $this->auth->getUserinfo()];
        $this->success(__('Logged in successful'), $data);
        //解析出来进行登陆
//        halt($data,$decryptData);
    }
    /**
     * AES解密（CBC模式）
     * @param string $encryptedData Base64编码的加密数据
     * @param string $key 密钥
     * @param string $iv 初始化向量
     * @return string 解密后的明文
     * @throws Exception
     */
    public function decrypt($encryptedData, $key, $iv)
    {
        // 确保密钥和 IV 的长度为 16 字节（AES-128）
//        $key = substr(hash('sha256', $key), 0, 32);
//        $iv = substr(hash('sha256', $iv), 0, 32);
//        $iv = openssl_random_pseudo_bytes(16);
        $key = str_pad(substr($key, 0, 16), 16, "0");
        $iv = str_pad(substr($iv, 0, 16), 16, "0");
//        dump($encryptedData,$key,$iv);
        // 解密数据
        $decryptedData = openssl_decrypt(
            base64_decode($encryptedData),
            'aes-128-cbc',
            $key,
            OPENSSL_RAW_DATA,
            $iv
        );

        // 返回解密后的明文
        return $decryptedData;
    }
}
